#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <time.h>

#define PORT 8006			
#define ADDR "192.168.43.218" 

int sock_fd;
struct sockaddr_in serv_addr;
void chatSend(void);
void chatRecv(void);

int main(int argc,char *argv[]){
    //创建套接字
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_fd < 0)
	{
		printf("create socket error!\n");
		return -1;
	}
	printf("create socket success!\n");
	
    //向服务器（特定的IP和端口）发起请求
    memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
    serv_addr.sin_family = AF_INET;  //使用IPv4地址
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);  //具体的IP地址
    serv_addr.sin_port = htons(atoi(argv[2]));  //端口

    // 连接服务器
	int ret = 0;
	ret = connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
	if(ret < 0)
	{
		printf("connect error!\n");
		return -1;
	}
	printf("connect success!\n");
	
	//线程
	pthread_t id1; // 定义一个线程 ID
	pthread_t id2;
	pthread_attr_t id1_attr; //定义属性变量
	
	pthread_attr_init(&id1_attr);
	pthread_attr_setscope(&id1_attr, PTHREAD_SCOPE_SYSTEM);
	//创建第一个线程
	ret = pthread_create(&id1, &id1_attr, (void*)&chatSend, NULL);
	if(ret != 0)
	{
		printf("pthread create fail!\n");
		return -1;
	}
		
	//创建第二个线程
	pthread_create(&id2, NULL, (void*)&chatRecv, NULL);
	printf("为chatSend创建的线程id为：%d\n",id1);
	printf("为chatRecv创建的线程id为：%d\n",id2);
	
	//有返回值
	void * retv;
	//没有返回值
	pthread_join(id1, NULL);
	pthread_join(id2, NULL);
	
    //关闭套接字
    close(sock_fd);
	return 0;
}
// 发送消息线程函数
void chatSend(void)
{
	int ret = 0;
	//发送数据到服务器
	char send_buff[256] = {0};
	printf("Welcome to chat!");
	do{
		printf("我：");
		scanf("%s",send_buff);
		ret = write(sock_fd, send_buff, sizeof(send_buff));
		if(ret < 0)
		{
			printf("send error!\n");
		}
		//printf("本次共发送%d个字符\n\n",ret);
	}while(1);
}
// 接收消息线程函数
void chatRecv(void)
{
	//读取服务器传回的数据
	int ret = 0;
	char recv_buff[128] = {0};
	do{
		ret = read(sock_fd, recv_buff, sizeof(recv_buff)-1);
		if(ret <= 0)
		{
			printf("recv error!\n");
			printf("对方可能已断开连接，正在尝试重新连接...\n");
			ret = connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
			if(ret < 0)
			{
				printf("connect error!\n");
			}else {
				printf("connect success!\n");
			}
			sleep(3);
		}else {
			//printf("\n本次共接收到%d个字符\n",ret);
			printf("对方回复: %s\n", recv_buff);
			memset(recv_buff, 0, sizeof(recv_buff));
		}
	}while(1);
}